const express = require('express');
const bcrypt = require('bcryptjs');
const { body, validationResult } = require('express-validator');
const { query, transaction } = require('../config/database');
const { authenticateToken } = require('../middleware/auth');
const multer = require('multer');
const path = require('path');
const fs = require('fs').promises;
const { mapInterests } = require('../utils/interests');
const router = express.Router();

// 配置头像上传
const avatarStorage = multer.diskStorage({
  destination: (req, file, cb) => {
    const uploadPath = path.join(__dirname, '../../uploads/avatars');
    cb(null, uploadPath);
  },
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, 'avatar-' + uniqueSuffix + path.extname(file.originalname));
  }
});

const avatarUpload = multer({ 
  storage: avatarStorage,
  limits: {
    fileSize: 2 * 1024 * 1024 // 2MB限制
  },
  fileFilter: (req, file, cb) => {
    // 只允许图片文件
    if (file.mimetype.startsWith('image/')) {
      cb(null, true);
    } else {
      cb(new Error('只允许上传图片文件'), false);
    }
  }
});

// 确保头像上传目录存在
const ensureAvatarDir = async () => {
  const uploadPath = path.join(__dirname, '../../uploads/avatars');
  try {
    await fs.access(uploadPath);
  } catch {
    await fs.mkdir(uploadPath, { recursive: true });
  }
};

// 初始化头像上传目录
ensureAvatarDir();

// 获取用户信息
router.get('/profile', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const user = await query(
      'SELECT id, username, email, gender, grade, major, dream_career, interests, avatar, created_at FROM users WHERE id = ?',
      [userId]
    );
    
    if (user.length === 0) {
      return res.status(404).json({ message: '用户不存在' });
    }
    
    const userData = user[0];
    // 处理兴趣爱好数据
    if (userData.interests) {
      // 如果interests已经是数组，直接使用；如果是JSON字符串，则解析
      if (typeof userData.interests === 'string') {
        try {
          userData.interests = JSON.parse(userData.interests);
        } catch (e) {
          userData.interests = [];
        }
      }
      // 映射旧版兴趣爱好到新版
      userData.interests = mapInterests(userData.interests);
    } else {
      userData.interests = [];
    }
    
    res.json({
      message: '获取用户信息成功',
      user: userData
    });
  } catch (error) {
    console.error('获取用户信息错误:', error);
    res.status(500).json({ message: '获取用户信息失败' });
  }
});

// 创建用户账号（新用户注册）
router.post('/account', [
  body('email').isEmail().withMessage('请输入有效的邮箱地址'),
  body('username').isLength({ min: 3, max: 20 }).withMessage('账号长度必须在3-20个字符之间'),
  body('password').isLength({ min: 6 }).withMessage('密码至少6个字符')
], async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ message: errors.array()[0].msg });
    }

    const { email, username, password } = req.body;

    // 检查邮箱是否已存在
    const existingEmail = await query(
      'SELECT id FROM users WHERE email = ?',
      [email]
    );

    if (existingEmail.length > 0) {
      return res.status(400).json({ message: '该邮箱已被注册' });
    }

    // 检查用户名是否已存在
    const existingUsername = await query(
      'SELECT id FROM users WHERE username = ?',
      [username]
    );

    if (existingUsername.length > 0) {
      return res.status(400).json({ message: '该用户名已被使用' });
    }

    // 加密密码
    const passwordHash = await bcrypt.hash(password, 12);

    // 创建用户 - 使用 transaction 确保数据一致性
    const userId = await transaction(async (connection) => {
      const [result] = await connection.execute(
        'INSERT INTO users (username, email, password_hash, is_verified) VALUES (?, ?, ?, ?)',
        [username, email, passwordHash, 1]
      );
      return result.insertId;
    });

    res.json({ 
      message: '账号创建成功',
      userId: userId
    });
  } catch (error) {
    console.error('创建账号错误:', error);
    res.status(500).json({ message: '创建账号失败' });
  }
});

// 更新用户信息
router.put('/profile', authenticateToken, [
  body('gender').optional().isIn(['male', 'female', 'other']).withMessage('性别值无效'),
  body('grade').optional().isLength({ max: 10 }).withMessage('年级信息过长'),
  body('major').optional().isLength({ max: 50 }).withMessage('专业信息过长'),
  body('dream_career').optional().isLength({ max: 50 }).withMessage('理想职业信息过长')
], async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ message: errors.array()[0].msg });
    }

    const userId = req.user.id;
    const { gender, grade, major, dream_career, interests } = req.body;

    // 处理兴趣爱好
    let interestsJson = null;
    if (interests && Array.isArray(interests)) {
      interestsJson = JSON.stringify(interests);
    }

    // 更新用户信息
    await query(
      'UPDATE users SET gender = ?, grade = ?, major = ?, dream_career = ?, interests = ? WHERE id = ?',
      [gender, grade, major, dream_career, interestsJson, userId]
    );

    res.json({ message: '个人信息更新成功' });
  } catch (error) {
    console.error('更新用户信息错误:', error);
    res.status(500).json({ message: '更新用户信息失败' });
  }
});

// 上传头像
router.post('/avatar', authenticateToken, avatarUpload.single('avatar'), async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({ message: '没有选择头像文件' });
    }

    const userId = req.user.id;
    const file = req.file;
    
    // 生成头像URL
    const avatarUrl = `/uploads/avatars/${file.filename}`;
    
    // 更新用户头像
    await query(
      'UPDATE users SET avatar = ? WHERE id = ?',
      [avatarUrl, userId]
    );

    res.json({ 
      message: '头像上传成功',
      avatar_url: avatarUrl
    });
  } catch (error) {
    console.error('头像上传失败:', error);
    res.status(500).json({ message: '头像上传失败' });
  }
});

module.exports = router;
